package com.dhecp.project.hr.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateDeleted;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.hr.domain.TrainingAppraiseLecturer;
import com.dhecp.project.hr.mapper.TrainingAppraiseLecturerMapper;
import com.dhecp.project.hr.service.TrainingAppraiseLecturerService;
import com.dhecp.project.system.domain.SysModuleTask;
import com.dhecp.project.system.mapper.SysModuleTaskMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 培训师评价表 服务层
 * @author DH-Xxj
 * @version 2020年4月22日
 */
@Service
public class TrainingAppraiseLecturerServiceImpl extends BaseModuleServiceImpl implements TrainingAppraiseLecturerService {

	@Autowired
	private TrainingAppraiseLecturerMapper businessMapper;
	
	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;
	
	@Autowired
	private SysModuleTaskMapper moduleTaskMapper;
	
	/**
	 * 查询前一单NID、BID
	 * @param nid 必要参数：当前 单据编码
	 * @return AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
	 * @author DH-Xxj
	 * @throws Exception  
	 */
	@Override
	public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (params.get("nid") == null || params.get("nid") == ""){
			params.put("nid", "0");   
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectLastNid(params);
        if (moduleNID == null){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
        	return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
    	dataMap.put("nid", moduleNID.getNid().toString());
    	dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
	}

	/**
	 * 查询后一单NID、BID
	 * @param nid 必要参数：当前 单据编码
	 * @return AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
	 * @author DH-Xxj
	 * @throws Exception  
	 */
	@Override
	public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
			return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectNextNid(params);
        if (moduleNID == null){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
        	return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
    	dataMap.put("nid", moduleNID.getNid().toString());
    	dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
	}
	
	/**
	 * 查询指定单nid的首记录
	 * @param params
	 * @return TrainingAppraiseLecturer
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public TrainingAppraiseLecturer queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
		return businessMapper.selectFirstRecordByNid(params);
	}

	/**
	 * 查询指定单nid的整单录
	 * @param nid 必要参数：当前 单据编码
	 * @return List - TrainingAppraiseLecturer
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public List<TrainingAppraiseLecturer> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return businessMapper.selectByNid(params);
	}
	
	/**
	 * 查询指定 guid 的单条记录
	 * @param guid 行唯一值
	 * @return TrainingAppraiseLecturer 实体
	 * @author DH-Xxj
	 */
	@Override
	public TrainingAppraiseLecturer queryByGuid(Map<String, Object> params) {
		return businessMapper.selectByGuid(params);
	}
	
	/**
	 * 查询需要当前用户评分的记录
	 * @param vPjZt 必要参数：评价状态（待评/草稿/已评/全部【vPjZt为空时】）
	 * @return List - TrainingAppraiseLecturer
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public List<TrainingAppraiseLecturer> queryListByCUser(Map<String, Object> params) throws Exception {
		if (params.get("vPjZt") != null && "全部".equals(params.get("vPjZt").toString())){
			params.put("vPjZt", "");
		}
		if (ShiroUtils.getUserLevel() < 6 && ShiroUtils.getMandatorLevel() < 6){	//非管理员级别只能查看自己的评价任务
			params.put("cUser", ShiroUtils.getMandatorId());
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        
        PageUtils.startPageStronger();
        return businessMapper.selectByCUser(params);
	}
	
	/**
	 * 查询
	 * @param params
	 * @return List - TrainingAppraiseLecturer
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
    public List<TrainingAppraiseLecturer> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.select(params);
    }
	
	/**
	 * 分组（整单）查询
	 * @param params
	 * @return List - TrainingAppraiseLecturer
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
    public List<TrainingAppraiseLecturer> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.selectgroup(params);
    }

	/**
	 * 保存
	 * @param moduleTable 必要参数：功能唯一标识
	 * @param infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
	 * @param infoItems 必要参数：对应实体类的json格式字符串
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@SuppressWarnings("unchecked")
	@Override
    public AjaxResult saveData(Map<String, Object> params) {
		params.put("businessEntity", new TrainingAppraiseLecturer());
		
		AjaxResult ajaxResult = this.saveDataBase(params);
		if (!"0".equals(ajaxResult.get("code").toString())){
			throw new RuntimeException(ajaxResult.get("msg").toString());
		}

		String resNid = "0";
		Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<TrainingAppraiseLecturer> businessDataList = (List<TrainingAppraiseLecturer>) ajaxResult.get("businessDataList");

    	List<RecordCheck> guidMapList = businessMapper.findRecords(infoMap.get("nid").toString());
    	Map<String, Object> guidMap = new HashMap<String, Object>();
    	if (!guidMapList.isEmpty() && guidMapList.size() > 0){
    		if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
    			throw new RuntimeException(MessageUtils.message("module.error.retry"));
    		}
        	for (RecordCheck recordCheck : guidMapList){
        		if (recordCheck != null && recordCheck.getGuid() != null){
            		guidMap.put(recordCheck.getGuid().toString(), "1");
        		}
        	}
    	}
    	
		if (businessDataList == null || businessDataList.size() == 0){
			resNid = "0";
		}else{
			resNid = infoMap.get("nid").toString();
	        for (TrainingAppraiseLecturer businessData : businessDataList) {
	        	String guid = "";
	        	if (businessData.getGuid() == null){
	        		guid = RandomValueUtils.getGUID();
	        		businessData.setGuid(guid);
	        	}else{
	        		guid = businessData.getGuid().toString();
	        	}
	        	
	        	for (String field : infoMap.keySet()){ //遍历非网格字段，并赋值到实体中
	        		Object fieldValue = infoMap.get(field);
	        		ReflectUtils.setValue(businessData, field, fieldValue);
	        	}
	        	
	        	if (guidMap.get(guid) == null){
	        		businessMapper.insert(businessData);
	        	}else{
	        		businessMapper.update(businessData);
	        		guidMap.remove(guid);
	        	}
	        }
		}
			
    	if (!guidMap.isEmpty()){
    		for (String guid : guidMap.keySet()){
    			businessMapper.delete(guid);
    		}
    	}
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }

	/**
	 * 删除
	 * @param params
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<TrainingAppraiseLecturer> businessDataList = JSON.parseArray(params.get("infoItems").toString(), TrainingAppraiseLecturer.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (TrainingAppraiseLecturer businessData : businessDataList) {
        	businessMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

	/**
	 * 修改删除标志（预留）
	 * @param infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
        	businessMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

	/**
	 * 流转  —— 添加流程任务、修改流程状态及生效标志
	 * @param tableDataId 必要参数：单据编码（nid）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		String nid = "0";
		if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
			return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
		}else{
			nid = params.get("tableDataId").toString();
		}
		params.put("nid", nid);
		List<TrainingAppraiseLecturer> businessDataList = businessMapper.selectByNid(params);
		if (businessDataList == null || businessDataList.size() == 0){
			return AjaxResult.error(MessageUtils.message("module.error.nodata"));
		}else{
			infoMap.put("cid", businessDataList.get(0).getCid());
			infoMap.put("bUser", businessDataList.get(0).getbUser());
			infoMap.put("bDept", businessDataList.get(0).getbDept());
			infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
			infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
			infoMap.put("createTime", businessDataList.get(0).getCreateTime());
			params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
			params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
		}
		
		//流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
    	if (params.get("optType") == null || params.get("optType") == ""){
    		params.put("optType", "go");
    	}
		UpdateFlow updateFlow = new UpdateFlow();
    	updateFlow = this.FlowDealBase(params);
		
        for (TrainingAppraiseLecturer businessData : businessDataList) {
        	updateFlow.setGuid(businessData.getGuid().toString());
        	businessMapper.updateFlow(updateFlow);
        }
        
        //生成评分者任务
        SysModuleTask moduleTask = new SysModuleTask();
        moduleTask.setbUser(ShiroUtils.getMandatorId());
        moduleTask.setpGuid(nid);
        moduleTask.setModuleTable("THR_TrainingAppraiseLecturer");        
        moduleTaskMapper.insertTask(moduleTask);

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

	/**
	 * 退回  —— 添加流程任务、修改流程状态及生效标志
	 * @param tableDataId 必要参数：单据编码（nid）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		String nid = "0";
		if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
			return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
		}else{
			nid = params.get("tableDataId").toString();
		}
		params.put("nid", nid);
		List<TrainingAppraiseLecturer> businessDataList = businessMapper.selectByNid(params);
		if (businessDataList == null || businessDataList.size() == 0){
			return AjaxResult.error(MessageUtils.message("module.error.nodata"));
		}else{
			infoMap.put("cid", businessDataList.get(0).getCid());
			infoMap.put("bUser", businessDataList.get(0).getbUser());
			infoMap.put("bDept", businessDataList.get(0).getbDept());
			infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
			infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
			infoMap.put("createTime", businessDataList.get(0).getCreateTime());
			params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
			params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
		}
		
		//流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
    	if (params.get("optType") == null || params.get("optType") == ""){
    		params.put("optType", "back");
    	}
		UpdateFlow updateFlow = new UpdateFlow();
    	updateFlow = this.FlowDealBase(params);
		
        for (TrainingAppraiseLecturer businessData : businessDataList) {
        	updateFlow.setGuid(businessData.getGuid().toString());
        	businessMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }
	
	/**
	 * 评分者评价（保存草稿/提交评价）
	 * @param infoItems 必要参数：对应实体类的json格式字符串
	 * @param vPjZt 必要参数：评价状态（草稿/已评）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updatePJ(Map<String, Object> params) {
		String vPjZt = ""; //评价状态（草稿/已评）
		String cUser = ""; //评分者工号
		if (params.get("vPjZt") == null || params.get("vPjZt") == ""){
			vPjZt = "草稿";
		}else{
			vPjZt = ("已评".equals(params.get("vPjZt").toString()) ? "已评" : "草稿");
		}
        List<TrainingAppraiseLecturer> businessDataList = JSON.parseArray(params.get("infoItems").toString(), TrainingAppraiseLecturer.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (TrainingAppraiseLecturer businessData : businessDataList) {
        	if (businessData.getcUser() == null){
        		cUser = "0000";
        	}else{
        		cUser = businessData.getcUser();
        	}
        	if (!cUser.equals(ShiroUtils.getMandatorId()) && !cUser.equals(ShiroUtils.getUserId())){
        		if (ShiroUtils.getMandatorLevel() < 6 && ShiroUtils.getUserLevel() < 6){
        			AjaxResult.warn("当前评价无需您处理。");
        		}
        	}
        	businessData.setvPjZt(vPjZt);
        	businessData.setfGrXx(businessData.getfGrXx1()+businessData.getfGrXx2()+businessData.getfGrXx3()+businessData.getfGrXx4());
        	businessData.setfKjPj(businessData.getfKjPj1()+businessData.getfKjPj2()+businessData.getfKjPj3()+businessData.getfKjPj4());
        	businessData.setfZhPj(businessData.getfZhPj1()+businessData.getfZhPj2()+businessData.getfZhPj3()+businessData.getfZhPj4());
        	businessData.setfSkBx(businessData.getfSkBx1()+businessData.getfSkBx2()+businessData.getfSkBx3()+businessData.getfSkBx4()+businessData.getfSkBx5()+businessData.getfSkBx6()+businessData.getfSkBx7()+businessData.getfSkBx8());
        	businessMapper.updatePJ(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
	
	/**
	 * 修改评价状态
	 * @param guid 行唯一值
	 * @param vPjZt 评价状态（待评/草稿/已评）
	 * @return
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult updateVPjZt(Map<String, Object> params) {
		if (params.get("guid") == null || params.get("guid") == ""){
			return AjaxResult.error("请提供需要修改评价状态的行guid值。");
		}
		if (params.get("vPjZt") == null || params.get("vPjZt") == ""){
			params.put("vPjZt", "草稿");
		}
		businessMapper.updateVPjZt(params);

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
	}

}
